/* 斗鱼的STT协议 */

export function serialize (data) {
  let ret = ''
  function _stringify (e, t) {
    let n = e ? r(e) + '@=' : ''
    ret += n + r(String(t)) + '/'
  }
  function r (e) {
    let text = ''
    for (let i = 0; e.length > i; i++) {
      if (e.charAt(i) === '/') text += '@S'
      else if (e.charAt(i) === '@') text += '@A'
      else text += e.charAt(i)
    }
    return text
  }
  if (data instanceof Array) {
    for (let i = 0; data.length > i; i++) _stringify(data[i].name, data[i].value)
    return ret
  }
  if (typeof data === 'object') {
    for (let key in data) _stringify(key, data[key])
    return ret
  }
}

export function unserialize (raw) {
  function _parse (raw) {
    let list = []
    if (raw.charAt(raw.length - 1) !== '/') raw += '/'

    let key = ''
    let value = ''
    for (let i = 0; raw.length > i; i++) {
      if (raw.charAt(i) === '/') {
        list.push({
          key: key,
          value: value
        })
        key = value = ''
      } else {
        if (raw.charAt(i) === '@') {
          i++
          if (raw.charAt(i) === 'A') {
            value += '@'
          } else if (raw.charAt(i) === 'S') {
            value += '/'
          } else if (raw.charAt(i) === '=') {
            key = value
            value = ''
          }
        } else {
          value += raw.charAt(i)
        }
      }
    }
    return list
  }

  let list = []
  raw = String(raw)
  if (raw) {
    list = _parse(raw)
    if (list.length === 1 && /@=/g.test(list[0].value)) {
      list = _parse(list[0].value)
    }
  }

  list.get = function (key) {
    if (typeof key === 'number') return this[key].value
    for (let i = 0; this.length > i; i++) {
      if (key === this[i].key) return this[i].value
    }
  }

  list.too = function too () {
    let obj = {}
    for (let i = 0; this.length > i; i++) {
      obj[this[i].key] = this[i].value
    }
    return obj
  }

  return list
}

export function isArraySTT (e) {
  let t = /@\S\//g
  let n = e.match(t)
  return !(!n || n.length === 1)
}
